package com.zyh;



import com.auth0.jwt.interfaces.DecodedJWT;
import com.zyh.util.JwtUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
//@Component
public class CheckAdminFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //提前判断是否是user模块
        ServerHttpRequest request = exchange.getRequest();
        String uri = request.getURI().toString();//请求路径
        if(uri.indexOf("/user-module/")>-1){
            return chain.filter(exchange);//放行请求
        }
        if(uri.indexOf("/admin/")>-1){
            //检查token里面的role是否为1
            //1.获取请求头里面的token，
            List<String> authorization = request.getHeaders().get("authorization");
            if(authorization!=null&&authorization.size()>0){
                String token = authorization.get(0);
                //2.判断token是否正确
                try{
                    DecodedJWT verify = JwtUtils.verify(token);
                    String role = verify.getClaim("role").asString();
                    if("1".equals(role)){//判断是否是管理员
                        return chain.filter(exchange);
                    }
                }catch (Exception e){
                    //拦截
                    exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
                    return exchange.getResponse().setComplete();
                }
            }
        }else{
            return chain.filter(exchange);//放行请求
        }

        //拦截
        exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
        return exchange.getResponse().setComplete();
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
